/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import request, { extend } from 'umi-request';
import { notification } from 'antd';
// cookies
import Cookies from 'js-cookie';
import { continueUpdateToken, updateXToken } from '@/utils/utils';

export const extendfn = extend

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '暂无权限',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

// response interceptor, chagne response
request.interceptors.request.use((url: string, options: any) => {
  // console.log(process.env.NODE_ENV);
  const token = Cookies.get('Authorization');
  if (token) {
    options.headers.Authorization = `Bearer ${token}`;
    // options.headers.Authorization = `${token}`;
  }
  options.headers.X_token = Cookies.get('X_token') || '';
  options.headers.webSide = '1'
  return {
    url,
    options: {
      ...options,
    },
  };
});

// handling error in response interceptor
request.interceptors.response.use((response: any, options: any) => {
  if (response.url.includes('/401') || response.status === 401) {
    notification.destroy();
    notification.error({
      message: '请求错误',
      description: '用户没有登录',
      // onClose: () => {
      //   Cookies.remove('Authorization');
      //   window.location.replace('/#/login');
      // },
    });
    Cookies.remove('Authorization');
    window.location.replace('/#/login');
    setTimeout(() => {
      window.location.reload();
    }, 500);
  } else {
    continueUpdateToken();
  }
  if (response.url.includes('/403') || response.status === 403) {
    notification.destroy();
    notification.error({
      message: '请求错误',
      description: '暂无权限',
      onClose: () => {
        // history.back();
        // window.location.replace('/#/login');
      },
    });
    // Cookies.remove('Authorization');
    // window.location.replace('/#/login');
    // setTimeout(() => {
    //   window.location.reload();
    // }, 500);
  }
  if (response && response.status !== 200) {
    const errorText = codeMessage[response.status] || response.statusText;
    notification.destroy();
    notification.error({
      message: '请求错误',
      description: errorText,
    });
  }
  return response;
});

// clone response in response interceptor
request.interceptors.response.use(async (response: any, options: any) => {
  const data = await response.clone().json();
  if (data && data.code !== 1) {
    notification.destroy();
    if (data.message && data.message.indexOf('未知错误') !== -1) {
      if (options.method === 'GET') {
        notification.error({
          message: '努力加载中！',
        });
      } else {
        notification.error({
          message: '未知错误',
        });
      }
    } else {
      notification.error({
        message: '请求错误',
        description: data.message,
      });
    }
  }
  return response;
});

export default request;
